import axios from 'axios';
import swal from 'sweetalert'
import router from "../router"

axios.defaults.withCredentials = true;
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
axios.defaults.validateStatus = function (status) {
    return status >= 200 && status < 300;
}

// white list里是可以重复请求的接口地址
const REQUEST_WHITE_LISTS = [
    "funkey/api/v2/Order/search",
    "funkey/api/v2/PriceCalendar/search"
]

// 判断该当前地址是否在白名单中
const hasInWhiteList = (url) => {
    for (let i=0; i<REQUEST_WHITE_LISTS.length; i++) {
        if (url.indexOf(REQUEST_WHITE_LISTS[i]) !== -1) {
            return true
        }
    }
    return false
}

let pending = []
const removeFromPending = (request) => {
    for (let i=0; i<pending.length; i++) {
        let oldRequest = pending[i]
        if (oldRequest.url === request.url + '&method=' + request.method) {
            oldRequest.cancel()
            pending.splice(i, 1)
            break;
        }
    }
}

/**
 * 全局request拦截器--- 处理重复请求
 */
axios.interceptors.request.use(request =>　{
    if (!hasInWhiteList(request.url)) {
        removeFromPending(request) // 去除重复请求
        request.cancelToken = new axios.CancelToken(c => {
            pending.push({url: request.url + "&method=" + request.method, cancel: c})
        })
    }
    return request
}, error => Promise.reject(error))


/**
 * 全局response拦截器--- 处理http返回的错误信息
 */
axios.interceptors.response.use(response => {
    // 未登录
    if (response.request.responseURL.indexOf("/accounts/login/?next=") !== -1) {
        router.app._router.push(`/login?redirect=${encodeURIComponent(router.app._route.fullPath)}`)
    }
    return response
}, error => {
    console.log(error)
    if (typeof error === 'object' && error.__CANCEL__) return; // 重复请求取消
    if (error && error.response) {
        if (error.response.status == 403) {
            swal({
                'title': "No Permission",
                'text': "",
                'icon': 'error'
            })
        } else {
            swal({
                'title': error.response.statusText,
                'text': "",
                'icon': 'error'
            })
        }

    } else {
        swal({
            'title': "Unknown Error",
            'text': "",
            'icon': 'error'
        })
    }
    return Promise.reject(error.response)
})